package com.cskaoyan.service;

import com.cskaoyan.bean.basebean.BaseParam;
import com.cskaoyan.bean.Ad;
import com.cskaoyan.bean.AdExample;
import com.cskaoyan.bean.basebean.BasePageData;
import com.cskaoyan.exception.AdException;
import com.cskaoyan.mapper.AdMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lxy
 * @create 2021-10-18 19:08
 */
@Service
public class AdServiceImpl implements AdService {

    @Autowired
    AdMapper adMapper;


    @Override
    public BasePageData query(String name, String content, BaseParam baseParam) {

        PageHelper.startPage(baseParam.getPage(),baseParam.getLimit());
        AdExample example = new AdExample();
        AdExample.Criteria criteria = example.createCriteria();

        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }

        if (content != null && !"".equals(content)) {
            criteria.andContentLike("%" + content + "%");
        }


        example.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());

        List<Ad> ads = adMapper.selectByExample(example);

        return BasePageData.ok(ads);
    }

    @Override
    public void deleteAd(Ad ad) throws AdException {
        ad.setDeleted(true);
        int i = adMapper.updateByPrimaryKeySelective(ad);
        if (i == 0) {
            throw new AdException();
        }
        return;
    }

    @Override
    public void updateAd(Ad ad) throws AdException {
        int i = adMapper.updateByPrimaryKeySelective(ad);
        if (i == 0) {
            throw new AdException();
        }
        return;
    }

    @Override
    public void createAd(Ad ad) throws AdException {
        int i = adMapper.insertSelective(ad);
        if (i == 0) {
            throw new AdException();
        }
        return;
    }
}
